//
//  AssetsCenter.m
//  cutter
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "AppData+User.h"
#import "AssetsCenterCtrl.h"
#import "ProductCenterCtrl.h"


#pragma mark -
#pragma mark AssetsMySourceCtrl
@implementation AssetsMySourceCell
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self.layer setMasksToBounds:YES];
        [self.layer setCornerRadius:4];
    }
    return self;
}
@end

@implementation AssetsMySourceCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    [self.backView setHidden:([self.dirid integerValue] == 0)];
    [self.backView addTarget:self action:@selector(backTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self reloadData];
}
-(void)reloadData{
    NSArray *controllers = [[self navigationController] viewControllers];
    if ([controllers count] > 1 && [controllers firstObject]==self) {
        [[self navigationController] popToRootViewControllerAnimated:NO];
    }
    //
    __weak AssetsMySourceCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this setData:[AppData userMatchAsset:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [this.collectionView reloadData];
        });
    });
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count] + (int)self.backView.hidden;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.backView.hidden && indexPath.item == 0) {
        AssetsMySourceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"newIdentifier" forIndexPath:indexPath];
        return cell;
    }
    //
    id item = [self.data objectAtIndex:indexPath.item - (int)self.backView.hidden];
    if ([[item objectForKey:@"isDir"] boolValue]) {
        AssetsMySourceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dirIdentifier" forIndexPath:indexPath];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"dirname"] lable:nil]];
        return cell;
    }
    //
    AssetsMySourceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"photoname"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    return cell;
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if([sender isKindOfClass:UICollectionViewCell.class]){
        UICollectionViewCell *cell = sender;
        if ([cell.reuseIdentifier isEqualToString:@"cellIdentifier"]) {
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
            if (indexPath){
                id item = [self.data objectAtIndex:indexPath.item - (int)self.backView.hidden];
                if ([[item objectForKey:@"isDir"] boolValue] == NO) {
                    if (self.onSelected) {
                        self.onSelected(self, item);
                    }
                }
            }
            return NO;
        }
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    UIPopoverPresentationController *popover = [segue.destinationViewController popoverPresentationController];
    if ([popover isKindOfClass:UIPopoverPresentationController.class]) {
        UIView *view = sender;
        [popover setSourceRect:view.bounds];
        [popover setSourceView:view];
        //
        __weak AssetsMySourceCtrl *blockSelf = self;
        AssetsPicker *ctrl = segue.destinationViewController;
        [ctrl setOnSelected:^(id sender, id result){
            if (result) {
                if ([result objectForKey:@"file"]) {
                    [MBProgressHUD showHUDAddedTo:blockSelf.view animated:YES];
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        id file = [AppData userMatchAssetEdit:result];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                            if (file) {
                                [blockSelf reloadData];
                            }
                        });
                    });
                }else{
                    [MBProgressHUD showHUDAddedTo:blockSelf.view animated:YES];
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        id directory = [AppData userMatchAssetDirectoryEdit:result];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                            if (directory) {
                                [blockSelf reloadData];
                            }
                        });
                    });
                }
            }
            [[sender navigationController] dismissViewControllerAnimated:YES completion:nil];
            [popover.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    //
    if ([segue.destinationViewController isKindOfClass:AssetsMySourceCtrl.class]) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath) {
            id item = [self.data objectAtIndex:indexPath.item - (int)self.backView.hidden];
            if ([[item objectForKey:@"isDir"] boolValue]) {
                AssetsMySourceCtrl *ctrl = segue.destinationViewController;
                [ctrl setDirid:[item objectForKey:@"id"]];
                [ctrl setOnSelected:self.onSelected];
            }
        }
    }
}
-(NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:self.dirid forKey:@"dirid"];
    return _condition;
}
-(void)backTouch:(UIButton*)sender{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end


#pragma mark -
#pragma mark AssetsSourceCtrl
@implementation AssetsSourceCell
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self.layer setMasksToBounds:YES];
        [self.layer setCornerRadius:4];
    }
    return self;
}
@end

@implementation AssetsSourceCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
}
-(void)reloadData{
    [self headerRefresh:nil];
}
- (void)headerRefresh:(TMRefresh*)sender{
    __weak AssetsSourceCtrl *this = self;
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userMatchResource:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.collectionView.footerView setFinish:NO];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak AssetsSourceCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        int p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userMatchResource:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *item = [self.data objectAtIndex:indexPath.item];
    AssetsSourceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"name"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"thumb400"] view:cell.imageView];
    return cell;
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if([sender isKindOfClass:UICollectionViewCell.class]){
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath && self.onSelected){
            self.onSelected(self, [self.data objectAtIndex:indexPath.item]);
        }
        return NO;
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *navigation = segue.destinationViewController;
        if ([[navigation.viewControllers firstObject] isKindOfClass:AssetsClassifyCtrl.class]) {
            __weak AssetsSourceCtrl *this = self;
            __weak AssetsClassifyCtrl *classify = [navigation.viewControllers firstObject];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [classify setData:[AppData userMatchResourceCate]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [classify.tableView reloadData];
                    [this headerRefresh:nil];
                    if ([classify.data count] > 0) {
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                        [classify.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
                    }
                });
            });
            [classify setOnSelected:^(id sender, id result){
                id iid = [result objectForKey:@"id"];
                if ([iid intValue] > 0) {
                    [this.condition setValue:iid forKey:@"type"];
                }else{
                    [this.condition setValue:nil forKey:@"type"];
                }
                [this headerRefresh:nil];
            }];
        }
    }
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(50) forKey:@"limit"];
    return _condition;
}
@end


#pragma mark -
#pragma mark AssetsCenterCtrl
@implementation AssetsCenterCtrl
- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self.productView addTarget:self action:@selector(onTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.favoriteView addTarget:self action:@selector(onTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.otherView addTarget:self action:@selector(onTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.selfView addTarget:self action:@selector(onTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self onTouch:self.productView];
    //
    [self.widthLayout setConstant:self.view.bounds.size.width];
    [self.view updateConstraintsIfNeeded];
}
-(UITabBar *)tabBar{
    UITabBar *temp = [super tabBar];
    [temp setFrame:CGRectZero];
    [temp setHidden:YES];
    return temp;
}
-(void)setSelectedIndex:(NSUInteger)selectedIndex{
    [super setSelectedIndex:selectedIndex];
    if (self.tabBarView) {
        [self.view addSubview:self.tabBarView];
    }
    [self setOnSelected:self.onSelected];
}
//
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *keyword = nil;
    if (isEmpty(textField.text) == NO) {
        keyword = textField.text;
    }
    //
    if ([self.selectedViewController isKindOfClass:ProductCenterCtrl.class]) {
        ProductCenterCtrl *ctrl = self.selectedViewController;
        [ctrl.condition setValue:keyword forKey:@"keyword"];
        [ctrl reloadData];
    }
    if ([self.selectedViewController isKindOfClass:ProductFavoriteCtrl.class]) {
        ProductFavoriteCtrl *ctrl = self.selectedViewController;
        [ctrl.condition setValue:keyword forKey:@"keyword"];
        [ctrl reloadData];
    }
    if ([self.selectedViewController isKindOfClass:AssetsSourceCtrl.class]) {
        AssetsSourceCtrl *ctrl = self.selectedViewController;
        [ctrl.condition setValue:keyword forKey:@"keyword"];
        [ctrl reloadData];
    }
    if ([self.selectedViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *root = self.selectedViewController;
        if ([[root.viewControllers firstObject] isKindOfClass:AssetsMySourceCtrl.class]) {
            AssetsMySourceCtrl *ctrl = [root.viewControllers firstObject];
            [ctrl.condition setValue:keyword forKey:@"keyword"];
            [ctrl reloadData];
        }
    }
    return YES;
}
-(void)setOnSelected:(blockEvent)onSelected{
    [self setTempSelected:onSelected];
    //
    if ([self.selectedViewController isKindOfClass:ProductCenterCtrl.class]) {
        ProductCenterCtrl *ctrl = self.selectedViewController;
        [self.searchView setText:[ctrl.condition objectForKey:@"keyword"]];
        [ctrl setOnSelected:onSelected];
        [ctrl setType:2];
        return;
    }
    if ([self.selectedViewController isKindOfClass:ProductFavoriteCtrl.class]) {
        ProductFavoriteCtrl *ctrl = self.selectedViewController;
        [ctrl setOnSelected:onSelected];
        [ctrl setType:2];
        return;
    }
    if ([self.selectedViewController isKindOfClass:AssetsSourceCtrl.class]) {
        AssetsSourceCtrl *ctrl = self.selectedViewController;
        [ctrl setOnSelected:onSelected];
        return;
    }
    if ([self.selectedViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *root = self.selectedViewController;
        if ([[root.viewControllers firstObject] isKindOfClass:AssetsMySourceCtrl.class]) {
            AssetsMySourceCtrl *ctrl = [root.viewControllers firstObject];
            [ctrl setOnSelected:onSelected];
            return;
        }
    }
}
-(blockEvent)onSelected{
    return self.tempSelected;
}
//
- (void)onTouch:(UIButton*)sender{
    NSArray *btns = @[self.productView,self.favoriteView,self.otherView,self.selfView];
    for (uint i=0;i<btns.count;i++) {
        UIButton *btn = btns[i];
        if (btn == sender) {
            if (i < 2) {
                [self.searchView setPlaceholder:@"搜索产品"];
            }else if (i > 2) {
                [self.searchView setPlaceholder:@"搜索个人素材"];
            }else{
                [self.searchView setPlaceholder:@"搜索素材"];
            }
            [self setSelectedIndex:i];
            [btn setSelected:YES];
        }else{
            [btn setSelected:NO];
        }
    }
}
@end
